﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Xml;
using System.Collections.Generic;

public partial class TaoBaoApi_TB_DownBaobei2 : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSMThemes();
    }
    private static string[,] _myParam = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string url = Request.Url.ToString();
            HttpRequest myRequest = new HttpRequest("url", url, url.Substring(url.IndexOf("?") + 1));            
            string user = myRequest.Params["user"];
            string type = myRequest.Params["type"];
            string showcase = myRequest.Params["showcase"];
            if (user == null || user.Length == 0)
                return;
            GetBaobeiList(user,type,showcase);            
        }
    }
    void GetBaobeiList(string user,string type,string showcase)
    {
        string pass = new TBCommon().GetTBPsdbyZH(user);
        if (pass == null || pass.Length == 0)
            return;
        
        txtUser.Text = user;
        txtpass.Text = pass;
        string errMsg = null;
        string sessionId = null;
        int ret = 0;
        string appkey = new TaoBaoAPI().GetAppKey(user);
        string certcode = new TaoBaoAPI().GetCertCode(user);
        ret = new TaoBaoAPI().GetTBSessionId(Page, user, pass, appkey, ref errMsg, ref sessionId);
        if (ret != 0)
        {
            new TBCommon().ShowMessage(Page, errMsg);
            return;
        }
        txtSession.Text = sessionId;
        string[,] param = new string[,] { {"page_size","1024"},{"page_no","1"},{ "nick", user }, { "method", "taobao.items.onsale.get" }, { "fields", "iid,title,cid,has_showcase,price" }, { "v", "1.0" },
            { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};
        string cid=null;
        if (type != null && type.Trim().Length > 0)
        {
            Model.TaoBao.TB_LEIMU m = new BLL.TaoBao.TB_LEIMU().GetModel(Convert.ToInt32(type));
            if (m != null)
                cid = m.LMDM;
        }
        if (cid != null)
        {
            param = new string[,] { {"page_size","1024"},{"page_no","1"},{ "nick", user }, { "method", "taobao.items.onsale.get" }, { "fields", "iid,title,cid,has_showcase,price" }, 
                    {"cid",cid},{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};
            if (showcase != null && showcase.Trim().Length > 0)
            {
                string show = null;
                if (showcase == "1")
                    show = "true";
                if (showcase == "2")
                    show = "false";
                if (show != null)
                    param = new string[,] { {"page_size","1024"},{"page_no","1"},{ "nick", user }, { "method", "taobao.items.onsale.get" }, { "fields", "iid,title,cid,has_showcase,price" }, 
                    {"has_showcase",show},{"cid",cid},{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};
            }
        }
        else
        {
            if (showcase != null && showcase.Trim().Length > 0)
            {
                string show = null;
                if (showcase == "1")
                    show = "true";
                if (showcase == "2")
                    show = "false";
                if (show != null)
                    param = new string[,] { {"page_size","1024"},{"page_no","1"},{ "nick", user }, { "method", "taobao.items.onsale.get" }, { "fields", "iid,title,cid,has_showcase,price" }, 
                    {"has_showcase",show},{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};
            }
        }
        _myParam = param;
        BS2.BSTaobaoAPI.TaobaoAPI.setAPPID(appkey);
        BS2.BSTaobaoAPI.TaobaoAPI.setCERTCODE(certcode);
        BS2.BSTaobaoAPI.TaobaoAPI.setLoginPro(user, pass);
        BS2.BSTaobaoAPI.TaobaoAPI.setSessionID(sessionId);
        XmlDocument xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param, user, pass, certcode);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
        {
            HttpCookie myCookie = Request.Cookies[user];
            if (myCookie != null)
            {
                myCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(myCookie);
            }
            new TBCommon().ShowMessage(Page, "下载淘宝数据失败，请返回上页再试一次。");
            btnDown.Enabled = false;
            return;
        }
        DataSet ds = new DataSet();
        ds.ReadXml(new XmlNodeReader(xml));
        if (ds != null)
        {
            DataTable dt = new DataTable();
            dt = ds.Tables["item"];            
            if (dt != null)
            {
                DataTable dt2 = new DataTable();
                foreach (DataColumn c in dt.Columns)
                    dt2.Columns.Add(c.ColumnName);
                //从dt中移除已经存在的宝贝            
                foreach (DataRow row in dt.Rows)
                {
                    if (new TBCommon().IsBaobeiExist(row["iid"].ToString(),new TBCommon().GetShopIdByZH(user)))
                        continue;
                    dt2.Rows.Add(row.ItemArray);                 
                }
                gvList.DataSource = dt2;
                gvList.DataBind();
                lbCount.Text = dt2.Rows.Count.ToString();
            }
            if (dt == null || gvList.Rows.Count == 0)
            {            
                ltInfo.Text = "<b>当前没有可下载的宝贝，造成此情况的原因可能为：</b><br />";
                ltInfo.Text += "1)宝贝已经下载到本地数据库，为了节约时间，不重复下载；<br />";
                ltInfo.Text += "2)当前淘宝商店没有宝贝；<br />";
                ltInfo.Text += "3)您的搜索条件有误，请返回上一页面，重新设置搜索条件后重试。<br />";
                btnDown.Enabled = false;              
            }
        }
    }
    protected void btnDown_Click(object sender, EventArgs e)
    {
        if (_myParam != null)
        {
            btnDown.Enabled = false;
            _myParam[4, 1] = "approve_status,iid,title,nick,type,cid,pic_path,num,props,valid_thru, list_time,price,has_discount,has_invoice," +
                        "has_warranty,has_showcase, modified,delist_time,postage_id,seller_cids ";
            new TB_BaoBei().DownTBBaoBei(txtUser.Text, txtpass.Text, new TaoBaoAPI().GetAppKey(txtUser.Text), new TaoBaoAPI().GetCertCode(txtUser.Text), txtSession.Text, _myParam);
        } 
        Response.Redirect("tb_bblink.aspx");
    }
   
    protected void chkAll_OnCheckedChanged(object sender, EventArgs e)
    {
        new TBCommon().chk_OnCheckedChanged(sender, e, gvList, "chkOne");
    }
    protected string GetShowCase(object o)
    {
        if (o is DBNull || o == null || o.ToString().Length == 0)
            return null;
        return o.ToString() == "true" ? "是" : "否";
    }
    
    protected string GetCidName(object o)
    {
        if (o is DBNull || o == null || o.ToString().Length == 0)
            return null;
        return new TBCommon().GetTBLeiMuNamebyCode(o.ToString());
    }
}
